/**
 * *************************************
 * Copyright(c)2016 Dingdang Yixia 
 * All Rights Reserved.
 *
 * @File: FaceosNotifyServiceImpl.java
 * @Package: com.ddyx.service.impl
 * @Description:
 * 
 * @Version: V1.0
 * @Author: Yidong.Xiang
 * @Date: 2017年8月27日 下午7:27:14
 * 
 * *************************************
 */
package com.ddyx.service.impl;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.TextMessage;

import org.springframework.stereotype.Service;

import com.ddyx.common.util.ImageFileUtil;
import com.ddyx.common.util.MD5FileUtil;
import com.ddyx.entity.FaceNotice;
import com.ddyx.entity.DynamicBlacklist;
import com.ddyx.entity.EventLog;
import com.ddyx.entity.Face;
import com.ddyx.entity.FaceSession;
import com.ddyx.entity.FaceSnapshot;
import com.ddyx.mapper.FaceNoticeMapper;
import com.ddyx.mapper.CustomerMapper;
import com.ddyx.mapper.DynamicBlacklistMapper;
import com.ddyx.mapper.EventLogMapper;
import com.ddyx.mapper.FaceMapper;
import com.ddyx.mapper.FaceSessionMapper;
import com.ddyx.mapper.FaceSnapshotMapper;
import com.ddyx.service.IFaceNotifyService;
import com.ddyx.service.base.BaseNodifyService;

/**
 * @ClassName: FaceosNotifyServiceImpl.java
 * @Module: Faceos人脸抓拍机集成模块
 * @Description: 
 * 
 * @author: Yidong.Xiang
 * @date: 2017年8月27日 下午7:27:14
 * 
 */
@Service("faceosNotifyService")
public class FaceosNotifyServiceImpl extends BaseNodifyService implements IFaceNotifyService {

	@Resource
	FaceMapper faceMapper;
	@Resource
	FaceNoticeMapper faceNoticeMapper;
	@Resource
	FaceSessionMapper faceSessionMapper;
	@Resource
	FaceSnapshotMapper faceSnapshotMapper;
	@Resource 
	CustomerMapper customerMapper;
	@Resource
	EventLogMapper eventLogMapper;
	@Resource
	DynamicBlacklistMapper dynamicBlacklistMapper;
	static String webappRoot = System.getProperty("webapp.root");
//	@Resource
//	JmsServerConfig config;
	int faceId = 0;//初始化为0，预防faceos系统手工上传黑名单异常。
	String _last_faceSessionNo = "";
	/* (non-Javadoc)
	 * @see com.ddyx.service.base.BaseNodifyService#doMessage(javax.jms.MapMessage)
	 */
	@Override
	public void doMessage(MapMessage mapMessage) {
		if(mapMessage==null)return;
		
		try {
			String ipcId = mapMessage.getString("IPC_ID");//网络摄像头ID
			String deviceId = mapMessage.getString("DeviceId");//摄像头主机设备ID
			int blackId = mapMessage.getInt("BlackID");//识别名单ID
			byte[] faceImage = mapMessage.getBytes("FaceImg");//人脸图像
			float score = mapMessage.getFloat("Score");//比对分值
			String searchResult = mapMessage.getString("SearchResult");//识别结果
			String collectTime = mapMessage.getString("CollectTime");//抓拍时间
			String imageUuid = MD5FileUtil.getMD5String(faceImage);//生成人脸头像MD5编码
			String faceSessionNo = mapMessage.getString("FaceId");//人脸识别编码，一个人识别一次的标识码
			
			
			//实现逻辑
			//p1:若不认识则写底库：新增人脸，新增黑名单记录，异步同步黑名单
			//   若认识则写通知：判断是否是Vip，是则写通知，
			//p2:写快照：新增记录
			//p3:写识别：若无faceSessionNo记录则新增，否则更新faceSessionNo记录score值比它低的face_id，snapshot_time，score
			//p4:生成人脸图片文件
			//p5:写事件日志
			
			
			//p1:begin
			
			if("false".equals(searchResult.toLowerCase()))//不认识过程
			{
//				Face face = new Face();
//				face.setFaceImage(faceImage);
//				face.setImageUuid(imageUuid);
//				String faceUuid = java.util.UUID.randomUUID().toString();
//				face.setFaceUuid(faceUuid);
//				faceId = faceMapper.insert(face);//新增人脸
				
				
				//p3:begin
				int session = faceSessionMapper.findByFaceSessionNo(faceSessionNo);//查找识别记录
				if(session==0)
				{

					Face face = new Face();
					face.setFaceImage(faceImage);
					face.setImageUuid(imageUuid);
					String faceUuid = java.util.UUID.randomUUID().toString();
					face.setFaceUuid(faceUuid);
					int r = faceMapper.insert(face);//新增人脸					
					faceId = face.getFaceId();
					FaceSession faceSession = new FaceSession();
					if(faceId>0)
						faceSession.setFaceId(faceId);
					faceSession.setFaceSessionNo(faceSessionNo);
					faceSession.setScore(BigDecimal.valueOf(score));
					faceSession.setSnapshotTime(collectTime);
					faceSession.setImageUuid(imageUuid);
					faceSessionMapper.insert(faceSession);//新增识别记录

					
					//新增黑名单记录
					if(faceId>0) {
						DynamicBlacklist blacklist = new DynamicBlacklist();
						blacklist.setBlacklistId(faceId);
						blacklist.setBlacklistPhoto(faceImage);
						dynamicBlacklistMapper.insert(blacklist);
						//异步同步黑名单
					}					
					
					//p5:begin
					EventLog event = new EventLog();
					if(faceId>0)
//						event.setContactId(contactId);
					event.setEventType("1");//1:进店,2:购买
					event.setEventTimestamp(collectTime);
					eventLogMapper.insert(event);
					//p5:end
				}
				else
				{
//					faceSessionMapper.updateBySessionNo(faceSessionNo, imageUuid, collectTime, score);
				}
				//p3:end
				
				
			}
			else//认识过程
			{
				//判断是否是Vip
				int hasVip = 0;//customerMapper.findVipByFaceId(blackId);
				if(hasVip>0)
				{
					Date date = new Date();
					FaceNotice notice = new FaceNotice();
//					notice.setContactId(contactId);
					notice.setMsec(date.getTime());//这个时间应该去抓拍时间
					notice.setImageUuid(imageUuid);
					notice.setNoticeDatetime(date);//这个时间应该去抓拍时间
					notice.setNoticeStatus(0);
					faceNoticeMapper.insert(notice);//新增Vip提醒通知
				}
			}
			//p1:end
			
			//p2:begin
			FaceSnapshot facesnap = new FaceSnapshot();
			facesnap.setIpcId(ipcId);
//			facesnap.setDeviceId(deviceId);
//			facesnap.setBlackId(blackId);
//			facesnap.setImageUuid(imageUuid);
//			if(faceId>0)
//				facesnap.setFaceId(faceId);
//			facesnap.setFaceSessionNo(faceSessionNo);
//			facesnap.setFaceImage(faceImage);
//			facesnap.setScore(BigDecimal.valueOf(score));
//			facesnap.setSearchResult(searchResult);
//			facesnap.setSnapshotTime(collectTime);
			faceSnapshotMapper.insert(facesnap);
			//p2:end
			

			
			//p4:begin
			File f = new File(webappRoot);
			String webappParent = f.getParent();
			StringBuffer path = new StringBuffer(webappParent)
					.append(File.separator).append("face")
					.append(File.separator).append("pic")
					.append(File.separator).append(imageUuid).append(".jpg");
			ImageFileUtil.byte2image(faceImage, path.toString());//生成人脸头像图片
			//p4:end
			
			
		} catch (JMSException e) {
			e.printStackTrace();
			return;
		}

	}

	/* (non-Javadoc)
	 * @see com.ddyx.service.base.BaseNodifyService#doMessage(javax.jms.TextMessage)
	 */
	@Override
	public void doMessage(TextMessage textMessage) {
		// TODO Auto-generated method stub

	}

	@Override
	public String getQueueName() {
		
		return "SaveFace";
	}

}
